var ctx;

function setCtx(ctx){
	this.ctx = ctx;
}

function mouseOverImage(target){
	$(target).attr("src","/manage/images/removemenu_red.png");
}
function mouseOutImage(target){
	$(target).attr("src","/manage/images/removemenu_green.png");
     }

var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    	//提交
    	function selectOk () {
    		var menus = zTree_Menu.getNodesByFilter(function(node){
  				if(node.checked){
  					return true;
  				}
  				
  				return false;
  			} , false , null , null);//getCheckedNodes();
    		var selectRm = [];
    		if(menus.length > 0){
    			for(var i = 0 ; i < menus.length ; i ++){
    				selectRm.push(menus[i].id);
        		}
    		}
    		
    		//无数据则造一条假数据,以免报错
    		if(selectRm.length == 0){
    			selectRm.push(0);
    		}
    		
    		//将所选菜单id数组传给父页面
   		 	parent.$('#selectRm').val(selectRm);
   	       //关闭窗口
   		 	parent.layer.close(index);
    	}
		
		var curMenu = null, zTree_Menu = null;
		var setting = {
			view: {
				showLine: true,
				showIcon: false,
				selectedMulti: false,
				dblClickExpand: false,
				addDiyDom: addDiyDom,
				fontCss: setFontCss_ztree,
			},
			edit: {
				enable: false,
				showRemoveBtn: false,
				showRenameBtn: false
				},
			data: {
				keep: {
					parent:true,
					leaf:true
				},
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "pId",
					rootPid: null 
				},
			},
			callback: {
				/* beforeClick: beforeClick, */
				onClick : onClick,
				onAsyncSuccess: zTreeOnAsyncSuccess,
				beforeDrag: beforeDrag,
				onCheck : onCheck,
			},check: {
		        enable: true,
		        chkboxType:{
		        	"Y":"ps",
		        	"N":"s"//子树都取消选中时，复树不变
		        }
		    }
		};

  		var zNodes;
  		
  		function onClick(event, treeId, treeNode, clickFlag) {  
  		   if(treeNode.checked){
   			  zTree_Menu.checkNode(zTree_Menu.getNodeByParam("id", treeNode.id, null), false, true, true);
   		   }else{
   			  zTree_Menu.checkNode(zTree_Menu.getNodeByParam("id", treeNode.id, null), true, true, true);
   		   }
  		}
  		
  		//点击勾选/取消勾选触发事件
  		function onCheck(event, treeId, treeNode) {  
  			var menus = zTree_Menu.getNodesByFilter(function(node){
  				if(node.checked){
  					return true;
  				}
  				
  				return false;
  			} , false , null , null);//.getCheckedNodes(true);
    		var selectRm = [];
    		if(menus.length > 0){
    			for(var i = 0 ; i < menus.length ; i ++){
    				selectRm.push(menus[i].id);
        		}
    		}
    		
  			refreshCheckedBox(selectRm);
  		}	
  		
 		function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
 			zNodes = JSON.parse(msg);
 			layer.msg(msg, {icon: 5});
 		};
 			
		function addDiyDom(treeId, treeNode) {
			var spaceWidth = 5;
			var switchObj = $("#" + treeNode.tId + "_switch"),
			icoObj = $("#" + treeNode.tId + "_ico");
			switchObj.remove();
			icoObj.before(switchObj);

			if (treeNode.level > 1) {
				var spaceStr = "<span style='display: inline-block;width:" + (spaceWidth * treeNode.level)+ "px'></span>";
				switchObj.before(spaceStr);
			}
		}

		
		var treeNodes;
		 
		function onLoadZTree(){
			 
			   $.ajax({
			    async:true,//是否异步
			    cache:false,//是否使用缓存
			    type:'post',//请求方式：post
			    dataType:'json',//数据传输格式：json
			    url:ctx + "/role/treeData?roleType=" + $("#roleType").val() + "&selectcells=" + $("#selectcells").val(),//请求的action路径
			    error:function(){
			      //请求失败处理函数
			      layer.msg('请求失败!', {icon: 5});
			    },
			    success:function(data){
			    	if(!data.success){
			    		layer.msg(data.msg, {icon: 5});
			    		return;
			    	}
			    	
			      var t = $("#treeDemo");
					 $.fn.zTree.init(t, setting, eval(data.msg));
					 
					 //初始化树时默认选择第一个节点
						zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
						
						//从后台传过来的当前角色绑定的菜单id集合
						var items = eval("("+ $("#menuList").val() +")");
						if(items.length > 0){
							for(var i = 0 ; i < items.length ; i ++){
								var node = zTree_Menu.getNodeByParam("id", items[i], null);
								
								if(node != undefined && node != null){
										//zTree_Menu.checkNode(node, true, false, false);
									node.checked = true;
									zTree_Menu.updateNode(node);
								}
							}
							
							refreshCheckedBox(items);
						}
						
						//展开所有
						zTree_Menu.expandAll(true);
			    }
			  });
			  
			  
			}
		
		$(document).ready(function(){
			onLoadZTree();
		});
		
		/**
	     * 刷新右边选中区域
	     * @param items 左边选中的集合 
	     */
	function refreshCheckedBox(items){
		//先清空
		$("#checkedRoleMenu").html("");
		if(items.length > 0){
			for(var i = 0 ; i < items.length ; i ++){
				var node = zTree_Menu.getNodeByParam("id", items[i], null);
				//不是父节点或者其子节点都未选中
				if(node != null && (!node.isParent || (node.isParent && IfNoChildrenCheck(node)))){
					var html = '<div id="menuId' + node.id + '" style="margin-top:12px;margin-left:12px;"><div style="float:left;">';
					if(node.getParentNode() != null){
						if(node.getParentNode().getParentNode() != null){
							if(node.getParentNode().getParentNode().getParentNode() != null){
								html += '<span>' +  node.getParentNode().getParentNode().getParentNode().name+ '</span>';
								html += '<span><img src="/manage/images/jianjiao.png" style="padding-left:4px;padding-right:4px"></span>';
							}
							
							html += '<span>' +  node.getParentNode().getParentNode().name+ '</span>';
							html += '<span><img src="/manage/images/jianjiao.png" style="padding-left:4px;padding-right:4px"></span>';
						}
						
						html += '<span>' +  node.getParentNode().name+ '</span>';
						html += '<span><img src="/manage/images/jianjiao.png" style="padding-left:4px;padding-right:4px"></span>';
					}
					
					html += '<span id='+ node.id +'>' + node.name + '</span>';
					html += '</div><div><span style="float:right;"> <img onmouseover="mouseOverImage(this)" onmouseout="mouseOutImage(this)"  onclick="removeMenu('+node.id+')" style="cursor:pointer;margin-right:12px;" src="/manage/images/removemenu_green.png"> </span>';
					html += '</div><span><br/></span></div>';
					$("#checkedRoleMenu").append(html);
				}
			}
		}
	}
	
	/**
     * 判断节点的子节点是否都未选中
     * @param node 当前节点
     */
	function IfNoChildrenCheck(node){
		if(node.children != null && node.children.length > 0){
			for(var child in node.children){
				if(node.children[child].checked){
					return false;
				}
			}
		}

		return true;
	}
	
	/**
     * 从右侧选中区删除
     * @param id 删除项的ID
     */
	function removeMenu(id){
		var node = zTree_Menu.getNodeByParam("id", id, null);
		if(node != undefined && node != null){
			zTree_Menu.checkNode(node, false, true, true);
		}
	}
			
		
		//==========================搜索树begin===================================//
		
		/**
     * 展开树
     * @param treeId  
     */
    function expand_ztree(treeId){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        treeObj.expandAll(true);
    }
     
    /**
     * 收起树：只展开根节点下的一级节点
     * @param treeId
     */
    function close_ztree(treeId){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        var nodes = treeObj.transformToArray(treeObj.getNodes());
        var nodeLength = nodes.length;
        for (var i = 0; i < nodeLength; i++) {
            if (nodes[i].id == '0') {
                //根节点：展开
                treeObj.expandNode(nodes[i], true, true, false);
            } else {
                //非根节点：收起
                treeObj.expandNode(nodes[i], false, true, false);
            }
        }
    }
     
    /**
     * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
     * @param treeId
     * @param searchConditionId 文本框的id
     */
    function search_ztree(treeId, searchConditionId){
        searchByFlag_ztree(treeId, searchConditionId, "");
    }
     
    /**
     * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
     * @param treeId
     * @param searchConditionId     搜索条件Id
     * @param flag                  需要高亮显示的节点标识
     */
    function searchByFlag_ztree(treeId, searchConditionId, flag){
        //<1>.搜索条件
        var searchCondition = $('#' + searchConditionId).val();
        //解决ie9以下placeholder与value重复的问题
    	if(searchCondition == $('#' + searchConditionId).attr("placeholder")){
    		searchCondition = "";
    	}
        //<2>.得到模糊匹配搜索条件的节点数组集合
        var highlightNodes = new Array();
        if (searchCondition != "") {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            highlightNodes = treeObj.getNodesByParamFuzzy("name", searchCondition, null);
        }
        //<3>.高亮显示并展示【指定节点s】
        highlightAndExpand_ztree(treeId, highlightNodes, flag);
        
        if (searchCondition == "") {
        	//展开所有
			zTree_Menu.expandAll(true);
        }
    }
     
    /**
     * 高亮显示并展示【指定节点s】
     * @param treeId
     * @param highlightNodes 需要高亮显示的节点数组
     * @param flag           需要高亮显示的节点标识
     */
    function highlightAndExpand_ztree(treeId, highlightNodes, flag){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        //<1>. 先把全部节点更新为普通样式
        var treeNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < treeNodes.length; i++) {
            treeNodes[i].highlight = false;
            treeObj.updateNode(treeNodes[i]);
        }
        //<2>.收起树, 只展开根节点下的一级节点
        close_ztree(treeId);
        //<3>.把指定节点的样式更新为高亮显示，并展开
        if (highlightNodes != null) {
            for (var i = 0; i < highlightNodes.length; i++) {
                if (flag != null && flag != "") {
                    if (highlightNodes[i].flag == flag) {
                        //高亮显示节点，并展开
                        highlightNodes[i].highlight = true;
                        treeObj.updateNode(highlightNodes[i]);
                        //高亮显示节点的父节点的父节点....直到根节点，并展示
                        var parentNode = highlightNodes[i].getParentNode();
                        var parentNodes = getParentNodes_ztree(treeId, parentNode);
                        treeObj.expandNode(parentNodes, true, true, false);
                        treeObj.expandNode(parentNode, true, true, false);
                    }
                } else {
                    //高亮显示节点，并展开
                    highlightNodes[i].highlight = true;
                    treeObj.updateNode(highlightNodes[i]);
                    //高亮显示节点的父节点的父节点....直到根节点，并展示
                    var parentNode = highlightNodes[i].getParentNode();
                    var parentNodes = getParentNodes_ztree(treeId, parentNode);
                    treeObj.expandNode(parentNodes, true, true, false);
                    treeObj.expandNode(parentNode, true, true, false);
                }
            }
        }
    }
     
    /**
     * 递归得到指定节点的父节点的父节点....直到根节点
     */
    function getParentNodes_ztree(treeId, node){
        if (node != null) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            var parentNode = node.getParentNode();
            return getParentNodes_ztree(treeId, parentNode);
        } else {
            return node;
        }
    }
     
    /**
     * 设置树节点字体样式
     */
     function setFontCss_ztree(treeId, treeNode) {
    	 
     }
     
     function beforeDrag(treeId, treeNodes) {
			return false;
	 }
